<template>
  <view class="container">
    <button type="primary" plain @click="handleShare">分享</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      shareData: {
        title: '分享标题',
        path: '/pages/home/home', // 分享后点击跳转的页面路径，支持携带参数，如：/pages/home/home?id=123
        imageUrl: '/static/share.png', // 分享卡片的封面图片，必须是本地图片，建议尺寸500x400，大小不超过128KB
        desc: '分享描述',
        success: function (res) {
          console.log('分享成功', res)
        },
        fail: function (res) {
          console.log('分享失败', res)
        }
      }
    }
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: this.shareData.title,
      path: this.shareData.path,
      imageUrl: this.shareData.imageUrl,
      desc: this.shareData.desc,
      success: res => {
        console.log('分享成功', res)
      },
      fail: res => {
        console.log('分享失败', res)
      }
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: this.shareData.title,
      query: 'from=timeline',
      imageUrl: this.shareData.imageUrl,
      success: res => {
        console.log('分享成功', res)
      },
      fail: res => {
        console.log('分享失败', res)
      }
    }
  },

  methods: {
    // 处理分享
    handleShare() {
      // #ifdef MP-WEIXIN
      uni.showActionSheet({
        itemList: ['分享给朋友', '分享到朋友圈'],
        success: res => {
          switch (res.tapIndex) {
            case 0:
              // 分享给朋友
              uni.share({
                provider: 'weixin',
                scene: 'WXSceneSession', // 分享场景：WXSceneSession-分享到聊天界面，WXSceneTimeline-分享到朋友圈
                type: 0,
                title: this.shareData.title,
                summary: this.shareData.desc,
                imageUrl: this.shareData.imageUrl,
                href: this.shareData.path,
                success: res => {
                  console.log('分享成功', res)
                },
                fail: res => {
                  console.log('分享失败', res)
                }
              })
              break
            case 1:
              // 分享到朋友圈
              uni.share({
                provider: 'weixin',
                scene: 'WXSceneTimeline',
                type: 0,
                title: this.shareData.title,
                summary: this.shareData.desc,
                imageUrl: this.shareData.imageUrl,
                href: this.shareData.path,
                success: res => {
                  console.log('分享成功', res)
                },
                fail: res => {
                  console.log('分享失败', res)
                }
              })
              break
          }
        }
      })
      // #endif

      // #ifndef MP-WEIXIN
      uni.showToast({
        title: '请在微信小程序中使用',
        icon: 'none'
      })
      // #endif
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 30rpx;
}
</style>
